package com.ddmh.p2p.socket.client;

import com.ddmh.p2p.socket.model.SharedFile;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * P2P客户端
 *
 * @author brant
 * @since 2024-04-12
 */
@Slf4j
public class Client {
    private final String serverAddress;
    private final int serverPort;
    private final List<SharedFile> sharedFiles;

    public Client(String serverAddress, int serverPort) {
        this.serverAddress = serverAddress;
        this.serverPort = serverPort;
        this.sharedFiles = new ArrayList<>();
    }

    public void start() {
        // 连接到P2P服务器并进行文件共享协议的交互
        try (Socket socket = new Socket(serverAddress, serverPort);
             ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream in = new ObjectInputStream(socket.getInputStream())) {
            log.info("Connected to P2P server at {}:{}", serverAddress, serverPort);

            // 向服务器注册共享文件列表
            out.writeObject(sharedFiles);

            // 循环等待来自其他客户端的下载请求
            while (true) {
                DownloadRequest request = (DownloadRequest) in.readObject();
                if (request != null) {
                    handleDownloadRequest(request);
                }
            }

        } catch (IOException | ClassNotFoundException e) {
            log.error("Error handling download request", e);
        }
    }

    private void handleDownloadRequest(DownloadRequest request) {
        // 根据请求中的文件名查找文件并发送数据给请求的客户端
        for (SharedFile file : sharedFiles) {
            if (file.getName().equals(request.getFileName())) {
                try (Socket dataSocket = new Socket(request.getRequestingClientAddress(),
                    request.getRequestingClientPort());
                     FileInputStream fileInputStream = new FileInputStream(file.getName());
                     OutputStream dataOutputStream = dataSocket.getOutputStream()) {

                    byte[] buffer = new byte[1024];
                    int bytesRead;

                    while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                        dataOutputStream.write(buffer, 0, bytesRead);
                    }
                } catch (IOException e) {
                    log.error("Error sending file data", e);
                }
            }
        }
    }

    public void addSharedFile(String filePath) {
        // 将文件添加到共享文件列表
        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            sharedFiles.add(new SharedFile(file.getName(), file.length()));
        }
    }
}